package com.yj.bj.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.yj.bj.constant.BankCode;
import com.yj.bj.constant.EasyConstant;
import com.yj.bj.constant.YJConstant;
import com.yj.bj.entity.BindEntity;
import com.yj.bj.entity.InstitutionEntity;
import com.yj.bj.entity.ProductEntity;
import com.yj.bj.entity.user.CardInformation;
import com.yj.bj.entity.user.MerChants;
import com.yj.bj.service.plan.BindService;
import com.yj.bj.service.plan.InstitutionService;
import com.yj.bj.service.plan.ProductService;
import com.yj.bj.service.user.MerChantsService;
import com.yj.bj.util.*;
import okhttp3.Response;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

/**
 * Created by bin on 2018/4/8.
 */
@RestController
@RequestMapping("/product/")
public class ProductController {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ProductController.class);
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    @Autowired
    private ProductService productService;
    @Autowired
    private SnowflakeIdWorker idWorker;
    @Autowired
    private MerChantsService merChantsService;
    @Autowired
    private InstitutionService institutionService;
    @Autowired
    private BindService bindService;

    @RequestMapping("merchantChange")
    public YJResult merchantChange(String merchantId,
                                   @RequestParam(defaultValue = "ld15") String aisleCode,
                                   String institutionId,
                                   String creditCardCode) throws Exception {
        InstitutionEntity in = institutionService.findByPrimaryKey(institutionId);
        MerChants mer = merChantsService.getMerRate(merchantId,aisleCode,in.getMerHost());
        if(mer == null){
            return YJResult.build(YJConstant.MER_NULL_CODE, YJConstant.MER_NULL_MSG,null);
        }
        BindEntity bindEntity = new BindEntity();
        bindEntity.setState("0000");
        bindEntity.setMerchantId(merchantId);
        bindEntity.setAisleCode(aisleCode);
        BindEntity bind = bindService.findByObject(bindEntity);
        if(bind == null){
            return YJResult.build("0001", "商户未开户");
        }
        String url = EasyConstant.host+"/bind/addProduct";
        HashMap<String,Object> map = Maps.newHashMap();
        map.put("institutionId",EasyConstant.spCode);
        map.put("aisleCode","ld15".equals(aisleCode)?EasyConstant.channelCode:aisleCode);
        map.put("outMerId",merchantId);
        map.put("aisleMerId",bind.getAisleMerId());
        map.put("rate",mer.getMerChantFee());
        map.put("d0Fee","100");
        map.put("creditCardCode",creditCardCode);
        map.put("sign",SignUtil.createYJSign(map));
        String result = HttpClientUtil.doPost(url,map);
        JSONObject job = JSONObject.parseObject(result);
        System.out.println(merchantId+"开产品"+result);
        logger.info(merchantId+"开产品"+result);
        if("0000".equals(job.getString("code"))){
            return YJResult.ok();
        }
        return YJResult.build(job.getString("code"),job.getString("msg"));
//        String orderNo = OrderUtil.createOrderNo(idWorker,"T");
//        // 获取令牌
//        BaseResMessage<TokenRes> tokenRes = new GetSpToken().token(EasyConstant.key, EasyConstant.spCode);
//        String token = tokenRes.getData().getToken();
//        // 解密令牌
//        String tokenClearText = EncryptUtil.desDecrypt(token, EasyConstant.key);
//
//
//        // 构建签名参数
//        TreeMap<String, Object> signParams = new TreeMap<String, Object>();
//        signParams.put("token", tokenClearText);
//        signParams.put("spCode", EasyConstant.spCode);
//        signParams.put("merchantCode", merchantCode);
//        signParams.put("channelCode", channelCode);
//        signParams.put("changeType", "2");
//        signParams.put("debitRate", mer.getMerChantFee());
//        signParams.put("debitCapAmount", "999999999");
//        signParams.put("creditRate", mer.getMerChantFee());
//        signParams.put("creditCapAmount", "999999999");
//
//
//        // 构建请求参数
//        JSONObject jsonObj = new JSONObject();
//        jsonObj.put("token", tokenClearText);
//        jsonObj.put("spCode", EasyConstant.spCode);
//        jsonObj.put("merchantCode", merchantCode);
//        jsonObj.put("channelCode", channelCode);
//        jsonObj.put("changeType", "2");
//        jsonObj.put("debitRate", mer.getMerChantFee());
//        jsonObj.put("debitCapAmount", "999999999");
//        jsonObj.put("creditRate", mer.getMerChantFee());
//        jsonObj.put("creditCapAmount", "999999999");
//        jsonObj.put("sign", SignUtil.signByMap(EasyConstant.key, signParams));
//
//        // 接口访问
//        String jsonReq = jsonObj.toJSONString();
//        System.out.println(sdf.format(new Date()) + "请求信息: " + jsonReq);
//
//        Response response = HttpUtil.sendPost(Constants.getServerUrl() + "/v2/merchant/merchantChange", jsonReq);
//        if (response.isSuccessful()) {
//            String jsonRsp = response.body().string();
//            logger.info(sdf.format(new Date()) + "响应信息: " + jsonRsp);
//            JSONObject job = JSONObject.parseObject(jsonRsp);
//            if("000000".equals(job.getString("code"))){
//                ProductEntity productEntity = new ProductEntity();
//                productEntity.setState(job.getString("code"));
//                productEntity.setMerchantId(merchantId);
//                productEntity.setChannelCode(channelCode);
//                productService.save(productEntity);
//                return YJResult.ok();
//            }
//            ProductEntity productEntity = new ProductEntity();
//            productEntity.setState(job.getString("code"));
//            productEntity.setMerchantId(merchantId);
//            productEntity.setChannelCode(channelCode);
//            productEntity.setRemark(job.getString("message"));
//            productService.save(productEntity);
//            return YJResult.ok();
//        } else {
//            logger.info(sdf.format(new Date()) + "响应码: " + response.code());
//        }
//        return YJResult.build(String.valueOf(response.code()),response.message());
    }

//    @RequestMapping("select")
//    public YJResult selects(String merchantId, String channelCode) {
//        ProductEntity productEntity = new ProductEntity();
//        productEntity.setState("000000");
//        productEntity.setMerchantId(merchantId);
//        productEntity.setChannelCode(channelCode);
//        productEntity = productService.findByObject(productEntity);
//        if(productEntity == null){
//            return YJResult.build("0001", "产品未开户");
//        }
//        return YJResult.ok(productEntity);
//    }
}
